﻿namespace HuwmanCode.ServiceProcess

open System
open System.ServiceProcess
open System.Runtime.InteropServices
open HuwmanCode
open HuwmanCode.Runtime.InteropServices
open HuwmanCode.Diagnostics.Logging

[<AutoOpen>]
module ServiceControllerExtension =
    let private getServiceConfig(scHandle:SafeHandle) =
        trace "Get service config" {
            let handle = scHandle.DangerousGetHandle()
            use infoMem = Marshal.allocGlobal 4096
            let mutable bytesNeeded = 0
            return QueryServiceConfig(handle, infoMem.Handle, 4096, &bytesNeeded)
                |> Bool.toOption (Marshal.PtrToStructure(infoMem.Handle, typeof<ServiceConfigInfo>) :?> ServiceConfigInfo) }

    type System.ServiceProcess.ServiceController with
        ///<summary>
        /// The executable path for the windows service
        ///</summary>
        member sc.ExecutablePath
            with public get() = 
                match sc.ServiceHandle |> getServiceConfig with
                | None -> failwith "Unable to query service config!"
                | Some info -> info.BinaryPathName